/***************** Base Object Extension *******************/
function add0(m){return m<10?'0'+m:m }
function date_format(t)
{
    //t是整数，否则要parseInt转换
    var time = new Date(t);
    var y = time.getFullYear();
    var m = time.getMonth()+1;
    var d = time.getDate();
    var h = time.getHours();
    var mm = time.getMinutes();
    var s = time.getSeconds();
    return y+'-'+add0(m)+'-'+add0(d);
}
function datetime_format(t)
{
    //t是整数，否则要parseInt转换
    var time = new Date(t);
    var y = time.getFullYear();
    var m = time.getMonth()+1;
    var d = time.getDate();
    var h = time.getHours();
    var mm = time.getMinutes();
    var s = time.getSeconds();
    return y+'-'+add0(m)+'-'+add0(d)+' '+add0(h)+':'+add0(mm)+':'+add0(s);
}
function http_build_query (formdata, url) { // eslint-disable-line camelcase
    //  discuss at: http://locutus.io/php/http_build_query/
    // original by: Kevin van Zonneveld (http://kvz.io)
    // improved by: Legaev Andrey
    // improved by: Michael White (http://getsprink.com)
    // improved by: Kevin van Zonneveld (http://kvz.io)
    // improved by: Brett Zamir (http://brett-zamir.me)
    //  revised by: stag019
    //    input by: Dreamer
    // bugfixed by: Brett Zamir (http://brett-zamir.me)
    // bugfixed by: MIO_KODUKI (http://mio-koduki.blogspot.com/)
    //      note 1: If the value is null, key and value are skipped in the
    //      note 1: http_build_query of PHP while in locutus they are not.
    //   example 1: http_build_query({foo: 'bar', php: 'hypertext processor', baz: 'boom', cow: 'milk'}, '', '&amp;')
    //   returns 1: 'foo=bar&amp;php=hypertext+processor&amp;baz=boom&amp;cow=milk'
    //   example 2: http_build_query({'php': 'hypertext processor', 0: 'foo', 1: 'bar', 2: 'baz', 3: 'boom', 'cow': 'milk'}, 'myvar_')
    //   returns 2: 'myvar_0=foo&myvar_1=bar&myvar_2=baz&myvar_3=boom&php=hypertext+processor&cow=milk'

    var value, key, tmp = [], argSeparator = '&';

    var _httpBuildQueryHelper = function (key, val, argSeparator) {
        var k, tmp = [];
        if (val === true) {
            val = '1';
        } else if (val === false) {
            val = '0';
        }
        if (val !== null) {
            if (typeof val === 'object') {
                for (k in val) {
                    if (val[k] !== null) {
                        tmp.push(_httpBuildQueryHelper(key + '[' + k + ']', val[k], argSeparator));
                    }
                }
                return tmp.join(argSeparator);
            } else if (typeof val !== 'function') {
                return encodeURIComponent(key) + '=' + encodeURIComponent(val);
            } else {
                throw new Error('There was an error processing for http_build_query().');
            }
        } else {
            return '';
        }
    };

    if (!argSeparator) {
        argSeparator = '&';
    }
    for (key in formdata) {
        value = formdata[key];
        var query = _httpBuildQueryHelper(key, value, argSeparator);
        if (query !== '') {
            tmp.push(query);
        }
        url = url.replace(new RegExp(key + '=[^&#]*&?', 'ig'), '');
    }

    url && (url = url.replace(/[&?]+$/, ''));
    var paramString = tmp.join(argSeparator);
    var result = !url ? '' : url + (!paramString ? '' : (url.indexOf('?') != -1 ? '&' : '?'));
    result += paramString;
    return result;
}

// Cookie Control
function setCookie(c_name,value,expiredays) {
    var exdate=new Date()
    exdate.setTime(exdate.getTime()+expiredays)
    document.cookie=c_name+ "=" +escape(value)+';path=/'+ ((expiredays==null) ? "" : ";expires="+exdate.toGMTString())
}
function getCookie(c_name) {
    if (document.cookie.length>0) {
        c_start=document.cookie.indexOf(c_name + "=")
        if (c_start!=-1)
        {
            c_start=c_start + c_name.length+1
            c_end=document.cookie.indexOf(";",c_start)
            if (c_end==-1) c_end=document.cookie.length
            return unescape(document.cookie.substring(c_start,c_end))
        }
    }
    return ""
};
// 四舍五入
Number.prototype.round = function (n) {
    var digit = Math.pow(10, n);
    return Math.round(this*digit)/digit;
};
// 进位取整
Number.prototype.ceil = function (n) {
    var digit = Math.pow(10, n);
    return Math.ceil(this*digit)/digit;
};
// 退位取整
Number.prototype.floor = function (n) {
    var digit = Math.pow(10, n);
    return Math.floor(this*digit)/digit;
}
// 去除前后空格
String.prototype.trim = function() {
    return this.replace( /(^\s*)|(\s*$)/g, '');
}
// 字符串转化为整型
String.prototype.toInt = function() {
    var num = parseInt(this);
    return isNaN(num) ? 0 : num;
}
// 字符串转化为浮点型
String.prototype.toFloat = function() {
    var num = parseFloat(this);
    return isNaN(num) ? 0 : num;
}
// 字符串截取替换
String.prototype.strCut = function(len, replaceWith) {
    var string = this;
    return string.length > len ? string.substr(0, len - 3) + (replaceWith || '...') : string;
}
// 首字母大写
String.prototype.ucFirst = function() {
    var string = this;
    return string[0].toUpperCase() + string.substr(1);
}
// 替换全部（ 仿 php preg_replace ）
String.prototype.replaceAll = function(from, to) {
    var string = this;
    for(var i in from) {
        var regexp = new RegExp(from[i], 'g');
        string = string.replace(regexp, to[i]);
    }
    return string;
}

// 删除其中一项（,隔开）
String.prototype.remove = function (value) {
    var separator = arguments[1] || ',';
    var dataArray = this.split(separator);

    var index = dataArray.indexOf(value);
    if(index >= 0) {
        dataArray.splice(index, 1);
    }

    return dataArray.join(separator);
}

// 字符格式化
String.prototype.number_format = Number.prototype.number_format = function (decimals, decPoint, thousandsSep) {
    var number = this;
    number = (number + '').replace(/[^0-9+\-Ee.]/g, '')
    var n = !isFinite(+number) ? 0 : +number
    var prec = !isFinite(+decimals) ? 0 : Math.abs(decimals)
    var sep = (typeof thousandsSep === 'undefined') ? ',' : thousandsSep
    var dec = (typeof decPoint === 'undefined') ? '.' : decPoint
    var s = ''

    var toFixedFix = function (n, prec) {
        var k = Math.pow(10, prec)
        return '' + (Math.round(n * k) / k)
            .toFixed(prec)
    }

    // @todo: for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.')
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep)
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || ''
        s[1] += new Array(prec - s[1].length + 1).join('0')
    }

    return s.join(dec);
};
// 对Date的扩展，将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
// 例子：
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1,                 //月份
        "d+": this.getDate(),                    //日
        "h+": this.getHours(),                   //小时
        "m+": this.getMinutes(),                 //分
        "s+": this.getSeconds(),                 //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds()             //毫秒
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}
function getQueryString(e) {
    var t = new RegExp("(^|&)" + e + "=([^&]*)(&|$)");
    var a = window.location.search.substr(1).match(t);
    if (a != null) return a[2];
    return ""
}
function addCookie(e, t, a) {
    var n = e + "=" + escape(t) + "; path=/";
    if (a > 0) {
        var r = new Date;
        r.setTime(r.getTime() + a * 3600 * 1e3);
        n = n + ";expires=" + r.toGMTString()
    }
    document.cookie = n
}
function setCookie(name, value, days) {
    var exp = new Date();
    exp.setTime(exp.getTime() + days * 24 * 60 * 60 * 1000);
    var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
    document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString();
}
function getCookie(e) {
    var t = document.cookie;
    var a = t.split("; ");
    for (var n = 0; n < a.length; n++) {
        var r = a[n].split("=");
        if (r[0] == e) return unescape(r[1])
    }
    return null
}
function delCookie(e) {
    var t = new Date;
    t.setTime(t.getTime() - 1);
    var a = getCookie(e);
    if (a != null) document.cookie = e + "=" + a + "; path=/;expires=" + t.toGMTString()
};
$(function() {
    // 下拉菜单带搜索
    var selectorWrap = null;
    var selectorContainer = null;
    var selector = null;
    var inputFilter = null;
    var selectConfirm = null;
    var selectObj = null;
    var changeCallback = function () {};
    var optionChangeCallback = function() {};
    var inputFilterCallback = function () {};
    $(document).on('click', '.sc-select', function () {
        selector = $(this);
        selectObj = selector.next('select');

        if(!selectorContainer) {
            var html = '<div><div class="sc-selector-bg"></div><div class="sc-selector-container">' +
                '<input type="text" class="text input-filter" data-target=".sc-selector-container ul" placeholder="请输入关键词">' +
                '<ul></ul><div class="sc-action"><a class="btn btn-small w-100" href="javascript:void(0);">确定</a></div>' +
                '</div></div>';
            selectorWrap = $(html).appendTo('body');

            // 隐藏选项
            selectorWrap.find('.sc-selector-bg').click(function () {
                selectorWrap.hide();
            });
            selectorContainer = selectorWrap.find('.sc-selector-container');

            selectorContainer.find('.sc-action').click(function () {
                changeCallback();
            });
            inputFilter = selectorWrap.find('.input-filter');
            inputFilter.on('input keyup', function () {
                inputFilterCallback();
            });
        }

        changeCallback = function () {
            selectObj.change(); // 触发change
            selectorWrap.hide();
        }

        // 输入过滤
        inputFilterCallback = function () {
            let url = selector.data('url');
            let keyword = inputFilter.val();
            let values = [];
            selectObj.find('option').each(function () {
                if($(this).prop('selected')) values.push($(this).val());
            });
            if(url) {
                $.getJSON(url, {
                    keyword: keyword,
                    values: values
                }, function (result) {
                    list = result.data;
                    let optionHtml = '';
                    if(!isMultiSelect) {
                        list.unshift({
                            key: '',
                            val: '请选择'
                        });
                    }
                    list.forEach(function (item) {
                        optionHtml += '<option value="'+item.key+'" '+(item.selected ? 'selected' : '')+'>'+item.val+'</option>';
                    });
                    selectObj.html(optionHtml);
                    optionChangeCallback();
                });
            }
        }

        var isMultiSelect = selector.hasClass('multi-select');
        if(isMultiSelect) {
            selectorContainer.addClass('sc-multi-select');
            selectorContainer.find('.sc-action').show();
        } else {
            selectorContainer.removeClass('sc-multi-select');
            selectorContainer.find('.sc-action').hide();
        }

        var position = $(this).offset();

        // 初始化
        selectorContainer.css({
            top: position.top + selector.outerHeight(),
            left: position.left,
            "min-width": $(this).outerWidth(),
            width: isMultiSelect ? (width > 500 ? width : 500) : 'auto'
        });

        selectorWrap.show().children('.sc-selector-bg').height($('body').height());

        if( selectObj.find('option:selected').length > 0) {
            var selectText = selectObj.find('option:selected').text();
            inputFilter.val(selectText);
        } else {
            selectorContainer.find('.input-filter').val('');
        }

        // 是否带条件过滤
        if(selector.hasClass('sc-select-filter')) {
            selectorContainer.addClass('sc-select-filter');
        } else {
            selectorContainer.removeClass('sc-select-filter');
        }

        optionChangeCallback = function () {
            selectorContainer.find('ul').html('');
            var selectOptions = selectObj.children();
            selectOptions.each(function () {
                var item = $(this);

                var content = item.text();
                var html = '<li class="sc-option">'+content+'</li>';
                var optionObj = $(html).data('content', content);

                // 默认选中项
                if(item.prop('selected')) {
                    optionObj.addClass('active');
                }

                // 选中
                optionObj.appendTo(selectorContainer.find('ul')).click(function () {
                    if(isMultiSelect) {
                        if(optionObj.hasClass('active')) {
                            item.prop('selected', false);
                            optionObj.removeClass('active');
                        } else {
                            item.prop('selected', true);
                            optionObj.addClass('active');
                        }
                    } else {
                        selectOptions.prop('selected', false);
                        item.prop('selected', true);
                        selectObj.change(); // 触发change
                        selectorWrap.hide();
                    }

                    // 所选的所有
                    var selectText = [];
                    selectOptions.filter(':selected').each(function () {
                        selectText.push($(this).text());
                    });
                    selector.text(selectText.join(','));
                });
            });
        }

        optionChangeCallback();
    });

    // 下拉选中
    $(document).on('change', '.sc-select + select', function () {
        var val = $(this).val();
        var text = $(this).find('option:selected').text();
        $(this).prev('.sc-select').html(text);
    });

    // 数据过滤
    $(document).on('input keyup', '.input-filter', function () {
        var keyword = $(this).val().trim();
        var reg = new RegExp(keyword);
        $($(this).data('target')).children().each(function () {
           var content = $(this).data('content');
           if(reg.test(content)) {
               $(this).show();
           } else {
               $(this).hide();
           }
       });
    });

    // 获取焦点时
    $(document).on('focus', '.input-num, .input-float', function () {
        var val = $(this).val().toFloat();
        if(val === 0) $(this).val('');
    });

    // 输入格式（整数）
    $('body').on('keyup', '.input-num', function () {
        var val = $(this).val();
        if(val === '') return;
        val = val.toInt();
        $(this).val(val);
    });
    // 输入格式（小数）
    $('body').on('keyup', '.input-float', function () {
        var max = $(this).data('max');
        var min = $(this).data('min');
        var digit = $(this).data('digit') || null;

        var val = $(this).val();

        if(val === '') return;

        var format_val = val.toFloat();
        if(!(/^\d+\.\d+$/.test(val))) {
            var endword = val[val.length - 1];
            val = val.toFloat();
            val += (endword == '.' ? '.' : '');
        } else if(digit !== null) { // 有效数位
            val = val.replace(new RegExp('(\\..{'+digit+'}).*$'), '$1');
        }

        if(max != null && format_val > max) {
            val = max;
        }
        if(min != null && format_val < min) {
            val = min;
        }

        $(this).val(val);
    });

    // 单选按钮点击自动查询
    $(document).on('click', '.btn-radio label', function () {
        var form = $(this).parents('form');
        if(form.length > 0) {
            setTimeout(function () {
                form.submit();
            }, 50);
        }
    });

    // 文件选择
    $('.type-file-file').change(function() {
        $(this).siblings('.type-file-text').val($(this).val().replace(/^.*?([^\\\/]+)$/, '$1'));
    });
    //自定义radio样式
    $(".cb-enable").click(function() {
        var parent = $(this).parents('.onoff');
        $('.cb-disable', parent).removeClass('selected');
        $(this).addClass('selected');
        $('.checkbox', parent).prop('checked', true);
    });
    $(".cb-disable").click(function() {
        var parent = $(this).parents('.onoff');
        $('.cb-enable', parent).removeClass('selected');
        $(this).addClass('selected');
        $('.checkbox', parent).prop('checked', false);
    });
});
$(function() {
    // 显示隐藏预览图 start
    $('.show_image').hover(
            function() {
                $(this).next().css('display', 'block');
            },
            function() {
                $(this).next().css('display', 'none');
            }
    );

    // 全选 start
    $('.checkall').click(function() {
        var _self = this.checked;
        $('.checkitem').each(function() {
            $(this).prop('checked', _self);
        });
        $('.checkall').prop('checked', _self);
    });

    // 表格鼠标悬停变色 start
    $("tbody tr").hover(
            function() {
                $(this).css({background: "#FBFBFB"});
            },
            function() {
                $(this).css({background: "#FFF"});
            });

    // 可编辑列（input）变色
    $('.editable').hover(
            function() {
                $(this).removeClass('editable').addClass('editable2');
            },
            function() {
                $(this).removeClass('editable2').addClass('editable');
            }
    );

    // 提示操作 展开与隐藏
    $("#checkZoom").click(function() {
        $(this).next("ul").toggle(800);
        $(this).find(".arrow").toggleClass("up");
    });

    // 可编辑列（area）变色
    $('.editable-tarea').hover(
            function() {
                $(this).removeClass('editable-tarea').addClass('editable-tarea2');
            },
            function() {
                $(this).removeClass('editable-tarea2').addClass('editable-tarea');
            }
    );

});


/* AJAX选择品牌 */
(function($) {
    $.fn.brandinit = function(options) {

        var brand_container = $(this);
        //根据首字母查询
        $(this).find('.letter[sctype="letter"]').find('a[data-letter]').click(function() {
            var _url = $(this).parents('.brand-index:first').attr('data-url');
            var _letter = $(this).attr('data-letter');
            var _search = $(this).html();
            $.getJSON(_url, {type: 'letter', letter: _letter}, function(data) {
                $(brand_container).insertBrand({param: data, search: _search});
            });
        });

        // 根据关键字查询
        $(this).find('.search[sctype="search"]').find('a').click(function() {
            var _url = $(this).parents('.brand-index:first').attr('data-url');
            var _keyword = $('#search_brand_keyword').val();
            $.getJSON(_url, {type: 'keyword', keyword: _keyword}, function(data) {
                $(brand_container).insertBrand({param: data, search: _keyword});
            });
        });
        // 选择品牌
        $(this).find('ul[sctype="brand_list"]').on('click', 'li', function() {
            $('#b_id').val($(this).attr('data-id'));
            $('#b_name').val($(this).attr('data-name'));
        });
        //搜索品牌列表滚条绑定
        $(this).find('div[sctype="brandList"]').perfectScrollbar();
    }
    $.fn.insertBrand = function(options) {
        //品牌搜索容器
        var dataContainer = $(this);
        $(dataContainer).find('div[sctype="brandList"]').show();
        $(dataContainer).find('div[sctype="noBrandList"]').hide();
        var _ul = $(dataContainer).find('ul[sctype="brand_list"]');
        _ul.html('');
        if ($.isEmptyObject(options.param)) {
            $(dataContainer).find('div[sctype="brandList"]').hide();
            $(dataContainer).find('div[sctype="noBrandList"]').show().find('strong').html(options.search);
            return false;
        }
        $.each(options.param, function(i, n) {
            $('<li data-id="' + n.brand_id + '" data-name="' + n.brand_name + '"><em>' + n.brand_initial + '</em>' + n.brand_name + '</li>').appendTo(_ul);
        });

        //搜索品牌列表滚条绑定
        $(dataContainer).find('div[sctype="brandList"]').perfectScrollbar('update');
    };
})(jQuery);


/**
 * layer 全屏弹出，用于线下订单
 */
function scLayerOpenFull(url, title, width, height, callbackdata = false){
    width  = width ? width + 'px' : '900px';
    height = height ? height + 'px' : '500px';

    let param = {
        type: 2,
        title: title,
        area: [width,height],
        fixed: false, // 不固定
        allowfullscreen:true,
        // maxmin: true,
        content: url,
        // 销毁后退出全屏
        end: function(){
            if (document.exitFullscreen) {
                document.exitFullscreen();
            } else if (document.msExitFullscreen) {
                document.msExitFullscreen();
            } else if (document.mozCancelFullScreen) {
                document.mozCancelFullScreen();
            } else if (document.webkitExitFullscreen) {
                document.webkitExitFullscreen();
            }
        }
    }

    // 先进入全屏，然后打开弹出层
    var element = document.documentElement;
    if (element.requestFullscreen) {
        element.requestFullscreen();
    } else if (element.msRequestFullscreen) {
        element.msRequestFullscreen();
    } else if (element.mozRequestFullScreen) {
        element.mozRequestFullScreen();
    } else if (element.webkitRequestFullscreen) {
        element.webkitRequestFullscreen();
    }

    let index = layer.open(param);
    layer.full(index);
}


/**
 * Layer 通用ifram弹出窗口
 */
function scLayerOpen(url, title, width, height, callbackdata = false) {
    // if (!width)  width  = '900px';
    // if (!height) height = '500px';
    width  = width ? width + 'px' : '900px';
    height = height ? height + 'px' : '500px';

    let param = {
        type: 2,
        title: title,
        area: [width,height],
        fixed: false, // 不固定
        maxmin: true,
        content: url
    }
    if (callbackdata) {
        param = {
            ... param,
            ...{btn: ['确定', '取消']},
            ...{btnAlign: 'c'},
            ...{
                yes: function(index) {
                    //当点击‘确定’按钮的时候，获取弹出层返回的值
                    var res = window["layui-layer-iframe" + index].callbackdata();
                    //打印返回的值，看是否有我们想返回的值。
                    callbackdata(res)
                    //最后关闭弹出层
                    layer.close(index)
                }},
            ...{
                cancel: function(index){
                    //右上角关闭回调
                    layer.close(index)
                }
            },
        }
    }
    layer.open(param);
}

/**
 * Layer 通用confirm弹出窗口
 * @param {type} url 链接地址
 * @param {type} msg 显示内容
 * @param {type} type 返回显示类型  默认未刷新当前页, Number类型为移除 id="sc_row_1" 中的内容  String类型为其他操作(reload\)
 * @returns {undefined}
 */
function scLayerConfirm(url, msg, type) {
    layer.confirm(msg, {
        btn: ['确定', '取消'],
        title: false,
    }, function () {
        $.ajax({
            url: url,
            type: "get",
            dataType: "json",
            success: function (data) {
                console.log(data);
                layer.msg(data.msg || data.message, {time: 1000}, function () {
                    if (data.code == 1 || data.code == 10000) {
                        if (typeof(type) == "undefined"){
                            location.reload();
                        }else if(typeof(type) == "number"){
                            $("#sc_row_"+type).remove();
                        }else if(typeof(type) == "string"){
                            if(type=="reload"){
                                location.reload();
                            }else{

                            }
                        }else{
                            alert("类型错误");
                        }
                    }
                });
            }
        });
    });
}

/**
 * 批量删除
 */
function submit_delete_batch() {
    /* 获取选中的项 */
    var items = '';
    $('.checkitem:checked').each(function () {
        items += this.value + ',';
    });
    if (items != '') {
        items = items.substr(0, (items.length - 1));
        submit_delete(items);
    }else{
        layer.alert('请勾选选项', {icon: 2})
    }
}

// 开关按钮
$(document).on('mousedown', '.on-off', function () {
    let thisObj = $(this);
    let notice = $(this).data('notice');
    if(notice && !window.closeLayerNotice) {
        //询问框
        layer.confirm(notice, {
            btn: ['确定','取消'] //按钮
        }, function(index){
            doOnOff(thisObj);
            layer.close(index);
        }, function(){

        });
    } else {
        doOnOff($(this));
    }
});

// 开关按钮
function doOnOff(thisObj) {
   console.log(thisObj);
    var maxStatus = thisObj.data('max-status') || 1;
    // 默认更改的值
    var defaultStatus = thisObj.data('states') || 1;
    var breakStatus = thisObj.data('break-states') || 0;
    var status = 0;
    var defaultOn = "on" + defaultStatus;
    var breakOn = "on" + breakStatus;
    if (defaultStatus > 1 && breakStatus == 0) {
        if (thisObj.hasClass(defaultOn)) {
            status = breakStatus;
        } else {
            status = defaultStatus;
        }
    } else if (defaultStatus == 1 && breakStatus) {
        if (thisObj.hasClass(breakOn)) {
            status = defaultStatus;
        }
        else {
            status = breakStatus;
        }
    } else if (defaultStatus > 1 && breakStatus) {
        if (thisObj.hasClass(defaultOn)) {
            status = breakStatus;
        } else if (thisObj.hasClass(breakOn)) {
            status = defaultStatus;
        } else {
            status = defaultStatus;
        }
    }
    else {
        for (var i = 1; i <= maxStatus; i++) {
            if (thisObj.hasClass('on')) {
                status = 1;
                break;
            }
            var c = 'on' + i;
            if (thisObj.hasClass(c)) {
                status = i;
                break;
            }
        }
        status = (status + 1) % (maxStatus + 1);
    }

    var dataType = thisObj.attr('data-type');
    var sendUrl = thisObj.attr('data-url');

    var data = {};
    data[dataType] = status;
    $.post(sendUrl, data, function (result) {
        if(result.code == 1) {
            thisObj.removeClass('on on1 on2 on3 on4');
            if (status) {
                var c = 'on' + status;
                c = "on " + c;
                /* c == 'on1' && (c = "on on1");*/
                thisObj.addClass(c);
            }
            layer.msg(result.msg);
        } else {
            layer.msg(result.msg);
        }

    });
}



/**
 * 打开文件上传对话框
 * @param dialog_title 对话框标题
 * @param callback 回调方法，参数有（当前dialog对象，选择的文件数组，你设置的extra_params）
 * @param extra_params 额外参数，object
 * @param multi 是否可以多选
 * @param filetype 文件类型，image,video,audio,file
 * @param app  应用名，CMF的应用名
 */
function openUploadDialog(dialog_title, callback, extra_params, multi, filetype, app) {
    Wind.css('artDialog');
    multi = multi ? 1 : 0;
    filetype = filetype ? filetype : 'image';
    app = app ? app : GV.APP;
    var params = '&multi=' + multi + '&filetype=' + filetype + '&app=' + app;
    Wind.use("artDialog", "iframeTools", function () {
        art.dialog.open(GV.ROOT + 'user/Asset/webuploader?' + params, {
            title: dialog_title,
            id: new Date().getTime(),
            width: '650px',
            height: '420px',
            lock: true,
            fixed: true,
            background: "#CCCCCC",
            opacity: 0,
            ok: function () {
                if (typeof callback == 'function') {
                    var iframewindow = this.iframe.contentWindow;
                    var files = iframewindow.get_selected_files();
                    if (files && files.length > 0) {
                        callback.apply(this, [this, files, extra_params]);
                    } else {
                        return false;
                    }

                }
            },
            cancel: true
        });
    });
}
/**
 * 单个文件上传
 * @param dialog_title 上传对话框标题
 * @param input_selector 图片容器
 * @param filetype 文件类型，image,video,audio,file
 * @param extra_params 额外参数，object
 * @param app  应用名,CMF的应用名
 */
function uploadOne(dialog_title, input_selector, filetype, extra_params, app) {
    openUploadDialog(dialog_title, function (dialog, files) {
        $(input_selector).val(files[0].filepath);
        $(input_selector + '-preview').attr('href', files[0].preview_url);
        $(input_selector + '-name').val(files[0].name);
    }, extra_params, 0, filetype, app);
}

// excel 导出
function export_xls(url) {
    location.href = url;
}

$(function () {

    // 下载 Excel
    $(document).on('mousedown', '.download-excel', function () {
        location.href = http_build_query({download: 1}, location.href);
    });
});
